﻿using System;
using System.Linq;
using Sponsorship.Domain;
using Raven.Client;
using Sponsorship.Domain.Sponsors;

namespace Sponsorship.ReadModel.Sponsors
{
    public class SponsorListItemEventHandler : 
            IEventHandler<SponsorEntered>,
            IEventHandler<SponsorChanged>,
            IEventHandler<SponsorDeleted>
    {
        private readonly IDocumentStore _documentStore;

        public SponsorListItemEventHandler(IDocumentStore documentStore)
        {
            _documentStore = documentStore;
        }

        public void Handle(SponsorEntered domainEvent)
        {
            using (IDocumentSession session = _documentStore.OpenSession())
            {
                var dto = new SponsorListItemDto
                {
                    AggregateRootId = domainEvent.SponsorId,
                    FirstName = domainEvent.FirstName,
                    LastName = domainEvent.LastName
                };

                session.Store(dto);

                session.SaveChanges(dto, domainEvent);
            }
        }

        public void Handle(SponsorDeleted domainEvent)
        {
            using (IDocumentSession session = _documentStore.OpenSession())
            {
                var dto = session.LoadById<SponsorListItemDto>(domainEvent.SponsorId);
                session.Delete(dto);
                session.SaveChanges();
            }
        }

        public void Handle(SponsorChanged domainEvent)
        {
            using (IDocumentSession session = _documentStore.OpenSession())
            {
                var dto = session.LoadById<SponsorListItemDto>(domainEvent.SponsorId);
                dto.FirstName = domainEvent.FirstName;
                dto.LastName = domainEvent.LastName;

                session.Store(dto);

                session.SaveChanges(dto, domainEvent);
            }
        }
    }
}
